package com.km.sglototo.util;

import com.km.sglototo.sys.entity.SysUser;
import net.sf.cglib.beans.BeanMap;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhaox
 * @Date 22/1/13
 */
public class BeanUtil {

    /**
     * 将对象转换为map
     *
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key.toString(), beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * Bean对象与Map相互转换
     * @param bean
     * @return
     */
    public static  Map<String, Object> converBean(Object bean) {
        Map<String, Object> map = new HashMap<>();
        Field field[] = bean.getClass().getDeclaredFields();

        try {
            Field.setAccessible(field, true);
            for(int i=0;i<field.length;i++){
                System.out.println(field[i].getName());
                System.out.println(field[i].get(bean));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }







    public static void main(String[] args) {
        SysUser user = new SysUser();
        user.setUsername("杨祖海");
        converBean(user);
        // Map<String,Object> map = beanToMap(user);
        // System.out.println(JsonUtil.objectToJson(user));
        // System.out.println(map.toString());
    }
}
